package com.cn.dim.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.dim.pojo.Dep;
import com.cn.dim.pojo.Info;
import com.cn.dim.pojo.Pages;
import com.cn.dim.service.InfoService;
import com.cn.dim.utils.TreeBuilder;
import com.github.pagehelper.Page;

@Controller
@RequestMapping("/info")
public class InfoController {

	@Resource
	private InfoService infoService;
	
	@RequestMapping(value ="/queryInfo",method = RequestMethod.GET)
	@ResponseBody
	//Pages是自己定义的分页类，此方法用于显示用户列表
	public Map<String,Object> queryInfo(HttpServletRequest request,Info i,Pages pages,String stime,String etime){
		//参数u是列表页中以查询条件数据临时组成的过渡Info对象
		Map<String,Object> param=new HashMap<>();//定义查询参数in
		Map<String,Object> reMap=new HashMap<>();//定义返回值，其中有一项必须是集合，先按照下面的写法做
		param.put("pageIndex", pages.getPage());
		param.put("pageSize", pages.getRows());
		param.put("info", i);
		
		if(stime!=null&&!stime.equals(""))
		{
			stime=stime+" 00:00:00";
		}
		if(etime!=null&&!etime.equals(""))
		{
			etime=etime+" 23:59:59";
		}
		param.put("stime", stime);
		param.put("etime", etime);
		
		try {
			Page<Map<String,Object>> rList = (Page)infoService.queryInfo(param);
			//下面代码通过循环对每一行的结果集补充“部门名称”与“职位名称”这两个显示字段
			for(Map m:rList){
				
				Map<String,Object> queryUserPara=new HashMap<>();//定义queryUser方法查询参数
				queryUserPara.put("infoid", m.get("id"));
				List<Map<String,Object>> users=infoService.queryUser(queryUserPara);//定义queryUser方法返回结果集对象
				
				String userShowStr=getuserShowStr(users);
				m.put("userShowStr", userShowStr);//在每行记录中补充1个用于显示的键值对
			}
			System.out.println(rList);
			reMap.put("rows", rList);
			reMap.put("total", rList.getTotal());
			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	//将用户的结果集转换为“某某,某某,某某”的形式（辅助方法）
	private String getuserShowStr(List<Map<String,Object>> users )
	{
		String userShowStr="";
		//循环这个权限（菜单）结果集
		for(Map user:users)
		{
			userShowStr=userShowStr+user.get("name")+",";
		}
		if(!userShowStr.equals(""))
		{
			userShowStr=userShowStr.substring(0, userShowStr.length()-1);//去掉最后一个逗号
		}
		return userShowStr;
	}
	
	@RequestMapping(value ="/insertInfo",method = RequestMethod.POST)
	@ResponseBody
	//此方法用于添加一个信息（第二个参数是对应的人员id集合）
	public Map<String,Object> insertInfo(Info i,String uids) 
	{
		String t=uids.substring(0, 1);
		if(t.equals(","))
		{
			uids=uids.substring(1, uids.length());
		}
		Map<String,Object> reMap=new HashMap<>();//返回值map
		String infoid=com.cn.dim.utils.StringUtil.makeUUID();
		i.setId(infoid);//主键
		i.setIsdel("0");//构造删除标记位
		
		JSONArray jsonArray=JSONArray.fromObject(uids);
        List<Map<String,Object>> i_us=(List<Map<String,Object>>)JSONArray.toList(jsonArray, Map.class);
        for(Map m:i_us)
        {
        	m.put("infoid", infoid);//构建插入中间表的数据
        }
		
		//这里补充创建人的id的代码
		
        try 
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String cdate_s = sdf.format(new Date());//创建日期
			Date cdate_d = sdf.parse(cdate_s);//创建日期
			i.setReletime(cdate_s);
			i.setCreatetime(cdate_d);
			
			int flag = infoService.insertInfo(i, i_us);
			if(flag>0)
			{
				reMap.put("message", "插入成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	//用于添加修改页中人员选择左侧的角色下拉；
	@RequestMapping(value ="/queryRole",method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String,Object>> queryRole(HttpServletRequest request){
		Map<String,Object> param=new HashMap<>();//构造一个空的参数；
		List<Map<String,Object>> list = new ArrayList<>();
		try {
			list =infoService.queryRole(param);
			//Map<String,Object> object=new HashMap<>();//这种方式只能将数据加到最后一行，用sql的union来解决
			//object.put("id", "0");
			//object.put("text", "全体员工");
			//list.add(object);
			//System.out.println();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return list;
	}

	//有子节点树形结构固定写法，不用太追究，用于添加修改页中人员选择左侧的“部门下拉”；
	@RequestMapping(value ="/queryDep",method = RequestMethod.GET)
	//这里不用写@ResponseBody了
	public String queryDep(HttpServletResponse response){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();//这一句并没有使用上
		List<Dep> rList = new ArrayList<>();
		Map<String,Object> params = new  HashMap<>();
		try
		{
			rList =infoService.queryDep(params);//这个params参数实际上没有用，是个空的摆设
			
			List<Dep> nodes = rList;
			String json  = new TreeBuilder().buildTree(nodes);
			
	        // 拼装树形json字符串
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.getWriter().write(json);
			response.getWriter().flush();
		}
		catch (IOException e){
			e.getStackTrace();
		}
		return null;
	}
	
	//根据参数中的infoid取对应的部门，用于修改页面回显
	@RequestMapping(value ="/queryUserByroleid",method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String,Object>> queryUserByroleid(HttpServletRequest request,String roleid){
		Map<String,Object> param=new HashMap<>();//查询参数是用户infoid；
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		param.put("roleid", roleid);
		try {
			list =infoService.queryUserByroleid(param);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return list;
	}
	
	//根据参数中的infoid取对应的部门，用于修改页面回显
	@RequestMapping(value ="/queryUserBydepid",method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> queryUserBydepid(HttpServletRequest request,String depid){
		Map<String,Object> param=new HashMap<>();//查询参数是用户infoid；
		Map<String,Object> reMap=new HashMap<>();
		param.put("depid", depid);
		try {
			List<Map<String,Object>> list =infoService.queryUserBydepid(param);
			reMap.put("data", list);
			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/updateInfo",method = RequestMethod.POST)
	@ResponseBody
	//此方法用于修改一个信息（第三个参数是对应的人员id集合，并且更新后中间表先删后插，都认为是没有阅读的；）
	public Map<String,Object> updateInfo(Info i,String infoid,String uids)  
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
		i.setId(infoid);//实体对象传来的并不含有id的值，这里需要要使用页面传过来infoid值进行填充；
		
		Map<String, Object> m=new HashMap<>();//构造删除中间表所用到的参数infoid键值对
		m.put("infoid", infoid);
        
		JSONArray jsonArray=JSONArray.fromObject(uids);
        List<Map<String,Object>> i_us=(List<Map<String,Object>>)JSONArray.toList(jsonArray, Map.class);
        for(Map mm:i_us)
        {
        	mm.put("infoid", i.getId());//构建插入中间表的数据
        }

        try 
		{
			int flag = infoService.updateInfo(i, m, i_us);
			if(flag>0)
			{
				reMap.put("message", "修改成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/delInfo",method = RequestMethod.POST)//这个POST有待商榷
	@ResponseBody
	public Map<String,Object> delInfo(HttpServletRequest request,String infoid) 
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
        Map<String,Object> m=new HashMap<>();//构造service接口中delInfo方法的参数
        m.put("infoid", infoid);
		
		//这里补充撤回（删除）人的id的代码
		
		try 
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date cdate = sdf.parse(sdf.format(new Date()));//修改（删除）日期
			m.put("updatetime", cdate);
			
			int flag = infoService.delInfo(m);
			if(flag>0)
			{
				reMap.put("message", "删除（撤回）成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/queryInfoById",method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> queryInfoById(HttpServletRequest request,String infoid){
		Map<String,Object> m=new HashMap<>();
		Map<String,Object> reMap=new HashMap<>();
		m.put("infoid", infoid);
		try {
			Info info =infoService.queryInfoById(m);
			reMap.put("data", info);
			reMap.put("status", "success");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}
	
	@RequestMapping(value ="/setInfo_UserIsRead",method = RequestMethod.POST)
	@ResponseBody
	//用于标记中间表针对某个员工已经阅读了消息，参数是infoid集合与userid，并组装在map中；
	public Map<String,Object> setInfo_UserIsRead(HttpServletRequest request,String userid,String iids)  
	{
		Map<String,Object> reMap=new HashMap<>();//返回值map
       
		JSONArray jsonArray=JSONArray.fromObject(iids);
        List<Map<String,Object>> i_us=(List<Map<String,Object>>)JSONArray.toList(jsonArray, Map.class);
        for(Map mm:i_us)
        {
        	mm.put("userid", userid);//构建插入中间表的数据
        }

        try 
		{
			int flag = infoService.setInfo_UserIsRead(i_us);
			if(flag>0)
			{
				reMap.put("message", "修改为已读状态成功");
				reMap.put("status", "success");
			}
			else
			{
				reMap.put("status", "error");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			reMap.put("status", "error");
		}
		return reMap;
	}

}
